ported clock skew fudge from 1.4
[lhc/web/wiklou.git] / includes / User.php
1 <?php
2 /**
3 * See user.txt
4 *
5 * @package MediaWiki
6 */
7
8 /**
9 *
10 */
11 require_once( 'WatchedItem.php' );
12
13 # Number of characters in user_token field
14 define( 'USER_TOKEN_LENGTH', 32 );
15
16 /**
17 *
18 * @package MediaWiki
19 */
20 class User {
21 /**#@+
22 * @access private
23 */
24 var $mId, $mName, $mPassword, $mEmail, $mNewtalk;
25 var $mEmailAuthenticated;
26 var $mRights, $mOptions;
27 var $mDataLoaded, $mNewpassword;
28 var $mSkin;
29 var $mBlockedby, $mBlockreason;
30 var $mTouched;
31 var $mToken;
32 var $mRealName;
33 var $mHash;
34 var $mGroups;
35
36 /** Construct using User:loadDefaults() */
37 function User() {
38 $this->loadDefaults();
39 }
40
41 /**
42 * Static factory method
43 * @param string $name Username, validated by Title:newFromText()
44 * @return User
45 * @static
46 */
47 function newFromName( $name ) {
48 $u = new User();
49
50 # Clean up name according to title rules
51
52 $t = Title::newFromText( $name );
53 if( is_null( $t ) ) {
54 return NULL;
55 } else {
56 $u->setName( $t->getText() );
57 $u->setId( $u->idFromName( $t->getText() ) );
58 return $u;
59 }
60 }
61
62 /**
63 * Factory method to fetch whichever use has a given email confirmation code.
64 * This code is generated when an account is created or its e-mail address
65 * has changed.
66 *
67 * If the code is invalid or has expired, returns NULL.
68 *
69 * @param string $code
70 * @return User
71 * @static
72 */
73 function newFromConfirmationCode( $code ) {
74 $dbr =& wfGetDB( DB_SLAVE );
75 $name = $dbr->selectField( 'user', 'user_name', array(
76 'user_email_token' => md5( $code ),
77 'user_email_token_expires > ' . $dbr->addQuotes( $dbr->timestamp() ),
78 ) );
79 if( is_string( $name ) ) {
80 return User::newFromName( $name );
81 } else {
82 return null;
83 }
84 }
85
86 /**
87 * Get username given an id.
88 * @param integer $id Database user id
89 * @return string Nickname of a user
90 * @static
91 */
92 function whoIs( $id ) {
93 $dbr =& wfGetDB( DB_SLAVE );
94 return $dbr->selectField( 'user', 'user_name', array( 'user_id' => $id ) );
95 }
96
97 /**
98 * Get real username given an id.
99 * @param integer $id Database user id
100 * @return string Realname of a user
101 * @static
102 */
103 function whoIsReal( $id ) {
104 $dbr =& wfGetDB( DB_SLAVE );
105 return $dbr->selectField( 'user', 'user_real_name', array( 'user_id' => $id ) );
106 }
107
108 /**
109 * Get database id given a user name
110 * @param string $name Nickname of a user
111 * @return integer|null Database user id (null: if non existent
112 * @static
113 */
114 function idFromName( $name ) {
115 $fname = "User::idFromName";
116
117 $nt = Title::newFromText( $name );
118 if( is_null( $nt ) ) {
119 # Illegal name
120 return null;
121 }
122 $dbr =& wfGetDB( DB_SLAVE );
123 $s = $dbr->selectRow( 'user', array( 'user_id' ), array( 'user_name' => $nt->getText() ), $fname );
124
125 if ( $s === false ) {
126 return 0;
127 } else {
128 return $s->user_id;
129 }
130 }
131
132 /**
133 * does the string match an anonymous IPv4 address?
134 *
135 * @static
136 * @param string $name Nickname of a user
137 * @return bool
138 */
139 function isIP( $name ) {
140 return preg_match("/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/",$name);
141 /*return preg_match("/^
142 (?:[01]?\d{1,2}|2(:?[0-4]\d|5[0-5]))\.
143 (?:[01]?\d{1,2}|2(:?[0-4]\d|5[0-5]))\.
144 (?:[01]?\d{1,2}|2(:?[0-4]\d|5[0-5]))\.
145 (?:[01]?\d{1,2}|2(:?[0-4]\d|5[0-5]))
146 $/x", $name);*/
147 }
148
149 /**
150 * does the string match roughly an email address ?
151 *
152 * @bug 959
153 *
154 * @param string $addr email address
155 * @static
156 * @return bool
157 */
158 function isValidEmailAddr ( $addr ) {
159 # There used to be a regular expression here, it got removed because it
160 # rejected valid addresses.
161 return ( trim( $addr ) != '' ) &&
162 (false !== strpos( $addr, '@' ) );
163 }
164
165 /**
166 * probably return a random password
167 * @return string probably a random password
168 * @static
169 * @todo Check what is doing really [AV]
170 */
171 function randomPassword() {
172 $pwchars = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz';
173 $l = strlen( $pwchars ) - 1;
174
175 $np = $pwchars{mt_rand( 0, $l )} . $pwchars{mt_rand( 0, $l )} .
176 $pwchars{mt_rand( 0, $l )} . chr( mt_rand(48, 57) ) .
177 $pwchars{mt_rand( 0, $l )} . $pwchars{mt_rand( 0, $l )} .
178 $pwchars{mt_rand( 0, $l )};
179 return $np;
180 }
181
182 /**
183 * Set properties to default
184 * Used at construction. It will load per language default settings only
185 * if we have an available language object.
186 */
187 function loadDefaults() {
188 static $n=0;
189 $n++;
190 $fname = 'User::loadDefaults' . $n;
191 wfProfileIn( $fname );
192
193 global $wgContLang, $wgIP, $wgDBname;
194 global $wgNamespacesToBeSearchedDefault;
195
196 $this->mId = 0;
197 $this->mNewtalk = -1;
198 $this->mName = $wgIP;
199 $this->mRealName = $this->mEmail = '';
200 $this->mEmailAuthenticated = null;
201 $this->mPassword = $this->mNewpassword = '';
202 $this->mRights = array();
203 $this->mGroups = array();
204 // Getting user defaults only if we have an available language
205 if( isset( $wgContLang ) ) {
206 $this->loadDefaultFromLanguage();
207 }
208
209 foreach( $wgNamespacesToBeSearchedDefault as $nsnum => $val ) {
210 $this->mOptions['searchNs'.$nsnum] = $val;
211 }
212 unset( $this->mSkin );
213 $this->mDataLoaded = false;
214 $this->mBlockedby = -1; # Unset
215 $this->setToken(); # Random
216 $this->mHash = false;
217
218 if ( isset( $_COOKIE[$wgDBname.'LoggedOut'] ) ) {
219 $this->mTouched = wfTimestamp( TS_MW, $_COOKIE[$wgDBname.'LoggedOut'] );
220 }
221 else {
222 $this->mTouched = '0'; # Allow any pages to be cached
223 }
224
225 wfProfileOut( $fname );
226 }
227
228 /**
229 * Used to load user options from a language.
230 * This is not in loadDefault() cause we sometime create user before having
231 * a language object.
232 */
233 function loadDefaultFromLanguage(){
234 $this->mOptions = User::getDefaultOptions();
235 }
236
237 /**
238 * Combine the language default options with any site-specific options
239 * and add the default language variants.
240 *
241 * @return array
242 * @static
243 * @access private
244 */
245 function getDefaultOptions() {
246 /**
247 * Site defaults will override the global/language defaults
248 */
249 global $wgContLang, $wgDefaultUserOptions;
250 $defOpt = $wgDefaultUserOptions + $wgContLang->getDefaultUserOptions();
251
252 /**
253 * default language setting
254 */
255 $variant = $wgContLang->getPreferredVariant();
256 $defOpt['variant'] = $variant;
257 $defOpt['language'] = $variant;
258
259 return $defOpt;
260 }
261
262 /**
263 * Get a given default option value.
264 *
265 * @param string $opt
266 * @return string
267 * @static
268 * @access public
269 */
270 function getDefaultOption( $opt ) {
271 $defOpts = User::getDefaultOptions();
272 if( isset( $defOpts[$opt] ) ) {
273 return $defOpts[$opt];
274 } else {
275 return '';
276 }
277 }
278
279 /**
280 * Get blocking information
281 * @access private
282 * @param bool $bFromSlave Specify whether to check slave or master. To improve performance,
283 * non-critical checks are done against slaves. Check when actually saving should be done against
284 * master.
285 *
286 * Note that even if $bFromSlave is false, the check is done first against slave, then master.
287 * The logic is that if blocked on slave, we'll assume it's either blocked on master or
288 * just slightly outta sync and soon corrected - safer to block slightly more that less.
289 * And it's cheaper to check slave first, then master if needed, than master always.
290 */
291 function getBlockedStatus( $bFromSlave = true ) {
292 global $wgIP, $wgBlockCache, $wgProxyList, $wgEnableSorbs, $wgProxyWhitelist;
293
294 if ( -1 != $this->mBlockedby ) { return; }
295
296 $this->mBlockedby = 0;
297
298 # User blocking
299 if ( $this->mId ) {
300 $block = new Block();
301 $block->forUpdate( $bFromSlave );
302 if ( $block->load( $wgIP , $this->mId ) ) {
303 $this->mBlockedby = $block->mBy;
304 $this->mBlockreason = $block->mReason;
305 $this->spreadBlock();
306 }
307 }
308
309 # IP/range blocking
310 if ( !$this->mBlockedby ) {
311 # Check first against slave, and optionally from master.
312 $block = $wgBlockCache->get( $wgIP, true );
313 if ( !$block && !$bFromSlave )
314 {
315 # Not blocked: check against master, to make sure.
316 $wgBlockCache->clearLocal( );
317 $block = $wgBlockCache->get( $wgIP, false );
318 }
319 if ( $block !== false ) {
320 $this->mBlockedby = $block->mBy;
321 $this->mBlockreason = $block->mReason;
322 }
323 }
324
325 # Proxy blocking
326 if ( !$this->isSysop() && !in_array( $wgIP, $wgProxyWhitelist ) ) {
327
328 # Local list
329 if ( array_key_exists( $wgIP, $wgProxyList ) ) {
330 $this->mBlockedby = wfMsg( 'proxyblocker' );
331 $this->mBlockreason = wfMsg( 'proxyblockreason' );
332 }
333
334 # DNSBL
335 if ( !$this->mBlockedby && $wgEnableSorbs ) {
336 if ( $this->inSorbsBlacklist( $wgIP ) ) {
337 $this->mBlockedby = wfMsg( 'sorbs' );
338 $this->mBlockreason = wfMsg( 'sorbsreason' );
339 }
340 }
341 }
342 }
343
344 function inSorbsBlacklist( $ip ) {
345 global $wgEnableSorbs;
346 return $wgEnableSorbs &&
347 $this->inDnsBlacklist( $ip, 'http.dnsbl.sorbs.net.' );
348 }
349
350 function inOpmBlacklist( $ip ) {
351 global $wgEnableOpm;
352 return $wgEnableOpm &&
353 $this->inDnsBlacklist( $ip, 'opm.blitzed.org.' );
354 }
355
356 function inDnsBlacklist( $ip, $base ) {
357 $fname = 'User::inDnsBlacklist';
358 wfProfileIn( $fname );
359
360 $found = false;
361 $host = '';
362
363 if ( preg_match( '/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/', $ip, $m ) ) {
364 # Make hostname
365 for ( $i=4; $i>=1; $i-- ) {
366 $host .= $m[$i] . '.';
367 }
368 $host .= $base;
369
370 # Send query
371 $ipList = gethostbynamel( $host );
372
373 if ( $ipList ) {
374 wfDebug( "Hostname $host is {$ipList[0]}, it's a proxy says $base!\n" );
375 $found = true;
376 } else {
377 wfDebug( "Requested $host, not found in $base.\n" );
378 }
379 }
380
381 wfProfileOut( $fname );
382 return $found;
383 }
384
385 /**
386 * Primitive rate limits: enforce maximum actions per time period
387 * to put a brake on flooding.
388 *
389 * Note: when using a shared cache like memcached, IP-address
390 * last-hit counters will be shared across wikis.
391 *
392 * @return bool true if a rate limiter was tripped
393 * @access public
394 */
395 function pingLimiter( $action='edit' ) {
396 global $wgRateLimits;
397 if( !isset( $wgRateLimits[$action] ) ) {
398 return false;
399 }
400 if( $this->isAllowed( 'delete' ) ) {
401 // goddam cabal
402 return false;
403 }
404
405 global $wgMemc, $wgIP, $wgDBname, $wgRateLimitLog;
406 $fname = 'User::pingLimiter';
407 $limits = $wgRateLimits[$action];
408 $keys = array();
409 $id = $this->getId();
410
411 if( isset( $limits['anon'] ) && $id == 0 ) {
412 $keys["$wgDBname:limiter:$action:anon"] = $limits['anon'];
413 }
414
415 if( isset( $limits['user'] ) && $id != 0 ) {
416 $keys["$wgDBname:limiter:$action:user:$id"] = $limits['user'];
417 }
418 if( $this->isNewbie() ) {
419 if( isset( $limits['newbie'] ) && $id != 0 ) {
420 $keys["$wgDBname:limiter:$action:user:$id"] = $limits['newbie'];
421 }
422 if( isset( $limits['ip'] ) ) {
423 $keys["mediawiki:limiter:$action:ip:$wgIP"] = $limits['ip'];
424 }
425 if( isset( $limits['subnet'] ) && preg_match( '/^(\d+\.\d+\.\d+)\.\d+$/', $wgIP, $matches ) ) {
426 $subnet = $matches[1];
427 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
428 }
429 }
430
431 $triggered = false;
432 foreach( $keys as $key => $limit ) {
433 list( $max, $period ) = $limit;
434 $summary = "(limit $max in {$period}s)";
435 $count = $wgMemc->get( $key );
436 if( $count ) {
437 if( $count > $max ) {
438 wfDebug( "$fname: tripped! $key at $count $summary\n" );
439 if( $wgRateLimitLog ) {
440 @error_log( wfTimestamp( TS_MW ) . ' ' . $wgDBname . ': ' . $this->getName() . " tripped $key at $count $summary\n", 3, $wgRateLimitLog );
441 }
442 $triggered = true;
443 } else {
444 wfDebug( "$fname: ok. $key at $count $summary\n" );
445 }
446 } else {
447 wfDebug( "$fname: adding record for $key $summary\n" );
448 $wgMemc->add( $key, 1, IntVal( $period ) );
449 }
450 $wgMemc->incr( $key );
451 }
452
453 return $triggered;
454 }
455
456 /**
457 * Check if user is blocked
458 * @return bool True if blocked, false otherwise
459 */
460 function isBlocked( $bFromSlave = false ) {
461 $this->getBlockedStatus( $bFromSlave );
462 return $this->mBlockedby !== 0;
463 }
464
465 /**
466 * Get name of blocker
467 * @return string name of blocker
468 */
469 function blockedBy() {
470 $this->getBlockedStatus();
471 return $this->mBlockedby;
472 }
473
474 /**
475 * Get blocking reason
476 * @return string Blocking reason
477 */
478 function blockedFor() {
479 $this->getBlockedStatus();
480 return $this->mBlockreason;
481 }
482
483 /**
484 * Initialise php session
485 */
486 function SetupSession() {
487 global $wgSessionsInMemcached, $wgCookiePath, $wgCookieDomain;
488 if( $wgSessionsInMemcached ) {
489 require_once( 'MemcachedSessions.php' );
490 } elseif( 'files' != ini_get( 'session.save_handler' ) ) {
491 # If it's left on 'user' or another setting from another
492 # application, it will end up failing. Try to recover.
493 ini_set ( 'session.save_handler', 'files' );
494 }
495 session_set_cookie_params( 0, $wgCookiePath, $wgCookieDomain );
496 session_cache_limiter( 'private, must-revalidate' );
497 @session_start();
498 }
499
500 /**
501 * Read datas from session
502 * @static
503 */
504 function loadFromSession() {
505 global $wgMemc, $wgDBname;
506
507 if ( isset( $_SESSION['wsUserID'] ) ) {
508 if ( 0 != $_SESSION['wsUserID'] ) {
509 $sId = $_SESSION['wsUserID'];
510 } else {
511 return new User();
512 }
513 } else if ( isset( $_COOKIE["{$wgDBname}UserID"] ) ) {
514 $sId = IntVal( $_COOKIE["{$wgDBname}UserID"] );
515 $_SESSION['wsUserID'] = $sId;
516 } else {
517 return new User();
518 }
519 if ( isset( $_SESSION['wsUserName'] ) ) {
520 $sName = $_SESSION['wsUserName'];
521 } else if ( isset( $_COOKIE["{$wgDBname}UserName"] ) ) {
522 $sName = $_COOKIE["{$wgDBname}UserName"];
523 $_SESSION['wsUserName'] = $sName;
524 } else {
525 return new User();
526 }
527
528 $passwordCorrect = FALSE;
529 $user = $wgMemc->get( $key = "$wgDBname:user:id:$sId" );
530 if($makenew = !$user) {
531 wfDebug( "User::loadFromSession() unable to load from memcached\n" );
532 $user = new User();
533 $user->mId = $sId;
534 $user->loadFromDatabase();
535 } else {
536 wfDebug( "User::loadFromSession() got from cache!\n" );
537 }
538
539 if ( isset( $_SESSION['wsToken'] ) ) {
540 $passwordCorrect = $_SESSION['wsToken'] == $user->mToken;
541 } else if ( isset( $_COOKIE["{$wgDBname}Token"] ) ) {
542 $passwordCorrect = $user->mToken == $_COOKIE["{$wgDBname}Token"];
543 } else {
544 return new User(); # Can't log in from session
545 }
546
547 if ( ( $sName == $user->mName ) && $passwordCorrect ) {
548 if($makenew) {
549 if($wgMemc->set( $key, $user ))
550 wfDebug( "User::loadFromSession() successfully saved user\n" );
551 else
552 wfDebug( "User::loadFromSession() unable to save to memcached\n" );
553 }
554 return $user;
555 }
556 return new User(); # Can't log in from session
557 }
558
559 /**
560 * Load a user from the database
561 */
562 function loadFromDatabase() {
563 global $wgCommandLineMode;
564 $fname = "User::loadFromDatabase";
565
566 # Counter-intuitive, breaks various things, use User::setLoaded() if you want to suppress
567 # loading in a command line script, don't assume all command line scripts need it like this
568 #if ( $this->mDataLoaded || $wgCommandLineMode ) {
569 if ( $this->mDataLoaded ) {
570 return;
571 }
572
573 # Paranoia
574 $this->mId = IntVal( $this->mId );
575
576 /** Anonymous user */
577 if( !$this->mId ) {
578 /** Get rights */
579 $this->mRights = $this->getGroupPermissions( array( '*' ) );
580 $this->mDataLoaded = true;
581 return;
582 } # the following stuff is for non-anonymous users only
583
584 $dbr =& wfGetDB( DB_SLAVE );
585 $s = $dbr->selectRow( 'user', array( 'user_name','user_password','user_newpassword','user_email',
586 'user_email_authenticated',
587 'user_real_name','user_options','user_touched', 'user_token' ),
588 array( 'user_id' => $this->mId ), $fname );
589
590 if ( $s !== false ) {
591 $this->mName = $s->user_name;
592 $this->mEmail = $s->user_email;
593 $this->mEmailAuthenticated = wfTimestampOrNull( TS_MW, $s->user_email_authenticated );
594 $this->mRealName = $s->user_real_name;
595 $this->mPassword = $s->user_password;
596 $this->mNewpassword = $s->user_newpassword;
597 $this->decodeOptions( $s->user_options );
598 $this->mTouched = wfTimestamp(TS_MW,$s->user_touched);
599 $this->mToken = $s->user_token;
600
601 $res = $dbr->select( 'user_groups',
602 array( 'ug_group' ),
603 array( 'ug_user' => $this->mId ),
604 $fname );
605 $this->mGroups = array();
606 while( $row = $dbr->fetchObject( $res ) ) {
607 $this->mGroups[] = $row->ug_group;
608 }
609 $effectiveGroups = array_merge( array( '*', 'user' ), $this->mGroups );
610 $this->mRights = $this->getGroupPermissions( $effectiveGroups );
611 }
612
613 $this->mDataLoaded = true;
614 }
615
616 function getID() { return $this->mId; }
617 function setID( $v ) {
618 $this->mId = $v;
619 $this->mDataLoaded = false;
620 }
621
622 function getName() {
623 $this->loadFromDatabase();
624 return $this->mName;
625 }
626
627 function setName( $str ) {
628 $this->loadFromDatabase();
629 $this->mName = $str;
630 }
631
632
633 /**
634 * Return the title dbkey form of the name, for eg user pages.
635 * @return string
636 * @access public
637 */
638 function getTitleKey() {
639 return str_replace( ' ', '_', $this->getName() );
640 }
641
642 function getNewtalk() {
643 $fname = 'User::getNewtalk';
644 $this->loadFromDatabase();
645
646 # Load the newtalk status if it is unloaded (mNewtalk=-1)
647 if( $this->mNewtalk == -1 ) {
648 $this->mNewtalk = 0; # reset talk page status
649
650 # Check memcached separately for anons, who have no
651 # entire User object stored in there.
652 if( !$this->mId ) {
653 global $wgDBname, $wgMemc;
654 $key = "$wgDBname:newtalk:ip:{$this->mName}";
655 $newtalk = $wgMemc->get( $key );
656 if( is_integer( $newtalk ) ) {
657 $this->mNewtalk = $newtalk ? 1 : 0;
658 return (bool)$this->mNewtalk;
659 }
660 }
661
662 $dbr =& wfGetDB( DB_SLAVE );
663 $res = $dbr->select( 'watchlist',
664 array( 'wl_user' ),
665 array( 'wl_title' => $this->getTitleKey(),
666 'wl_namespace' => NS_USER_TALK,
667 'wl_user' => $this->mId,
668 'wl_notificationtimestamp != 0' ),
669 'User::getNewtalk' );
670 if( $dbr->numRows($res) > 0 ) {
671 $this->mNewtalk = 1;
672 }
673 $dbr->freeResult( $res );
674
675 if( !$this->mId ) {
676 $wgMemc->set( $key, $this->mNewtalk, time() ); // + 1800 );
677 }
678 }
679
680 return ( 0 != $this->mNewtalk );
681 }
682
683 function setNewtalk( $val ) {
684 $this->loadFromDatabase();
685 $this->mNewtalk = $val;
686 $this->invalidateCache();
687 }
688
689 function invalidateCache() {
690 global $wgClockSkewFudge;
691 $this->loadFromDatabase();
692 $this->mTouched = wfTimestamp(TS_MW, time() + $wgClockSkewFudge );
693 # Don't forget to save the options after this or
694 # it won't take effect!
695 }
696
697 function validateCache( $timestamp ) {
698 $this->loadFromDatabase();
699 return ($timestamp >= $this->mTouched);
700 }
701
702 /**
703 * Salt a password.
704 * Will only be salted if $wgPasswordSalt is true
705 * @param string Password.
706 * @return string Salted password or clear password.
707 */
708 function addSalt( $p ) {
709 global $wgPasswordSalt;
710 if($wgPasswordSalt)
711 return md5( "{$this->mId}-{$p}" );
712 else
713 return $p;
714 }
715
716 /**
717 * Encrypt a password.
718 * It can eventuall salt a password @see User::addSalt()
719 * @param string $p clear Password.
720 * @param string Encrypted password.
721 */
722 function encryptPassword( $p ) {
723 return $this->addSalt( md5( $p ) );
724 }
725
726 # Set the password and reset the random token
727 function setPassword( $str ) {
728 $this->loadFromDatabase();
729 $this->setToken();
730 $this->mPassword = $this->encryptPassword( $str );
731 $this->mNewpassword = '';
732 }
733
734 # Set the random token (used for persistent authentication)
735 function setToken( $token = false ) {
736 global $wgSecretKey, $wgProxyKey, $wgDBname;
737 if ( !$token ) {
738 if ( $wgSecretKey ) {
739 $key = $wgSecretKey;
740 } elseif ( $wgProxyKey ) {
741 $key = $wgProxyKey;
742 } else {
743 $key = microtime();
744 }
745 $this->mToken = md5( $wgSecretKey . mt_rand( 0, 0x7fffffff ) . $wgDBname . $this->mId );
746 } else {
747 $this->mToken = $token;
748 }
749 }
750
751
752 function setCookiePassword( $str ) {
753 $this->loadFromDatabase();
754 $this->mCookiePassword = md5( $str );
755 }
756
757 function setNewpassword( $str ) {
758 $this->loadFromDatabase();
759 $this->mNewpassword = $this->encryptPassword( $str );
760 }
761
762 function getEmail() {
763 $this->loadFromDatabase();
764 return $this->mEmail;
765 }
766
767 function getEmailAuthenticationTimestamp() {
768 $this->loadFromDatabase();
769 return $this->mEmailAuthenticated;
770 }
771
772 function setEmail( $str ) {
773 $this->loadFromDatabase();
774 $this->mEmail = $str;
775 }
776
777 function getRealName() {
778 $this->loadFromDatabase();
779 return $this->mRealName;
780 }
781
782 function setRealName( $str ) {
783 $this->loadFromDatabase();
784 $this->mRealName = $str;
785 }
786
787 function getOption( $oname ) {
788 $this->loadFromDatabase();
789 if ( array_key_exists( $oname, $this->mOptions ) ) {
790 return $this->mOptions[$oname];
791 } else {
792 return '';
793 }
794 }
795
796 function setOption( $oname, $val ) {
797 $this->loadFromDatabase();
798 if ( $oname == 'skin' ) {
799 # Clear cached skin, so the new one displays immediately in Special:Preferences
800 unset( $this->mSkin );
801 }
802 $this->mOptions[$oname] = $val;
803 $this->invalidateCache();
804 }
805
806 function getRights() {
807 $this->loadFromDatabase();
808 return $this->mRights;
809 }
810
811 /**
812 * Get the list of explicit group memberships this user has.
813 * The implicit * and user groups are not included.
814 * @return array of strings
815 */
816 function getGroups() {
817 $this->loadFromDatabase();
818 return $this->mGroups;
819 }
820
821 /**
822 * Get the list of implicit group memberships this user has.
823 * This includes all explicit groups, plus 'user' if logged in
824 * and '*' for all accounts.
825 * @return array of strings
826 */
827 function getEffectiveGroups() {
828 $base = array( '*' );
829 if( $this->isLoggedIn() ) {
830 $base[] = 'user';
831 }
832 return array_merge( $base, $this->getGroups() );
833 }
834
835 /**
836 * Remove the user from the given group.
837 * This takes immediate effect.
838 * @string $group
839 */
840 function addGroup( $group ) {
841 $dbw =& wfGetDB( DB_MASTER );
842 $dbw->insert( 'user_groups',
843 array(
844 'ug_user' => $this->getID(),
845 'ug_group' => $group,
846 ),
847 'User::addGroup',
848 array( 'IGNORE' ) );
849
850 $this->mGroups = array_merge( $this->mGroups, array( $group ) );
851 $this->mRights = User::getGroupPermissions( $this->getEffectiveGroups() );
852
853 $this->invalidateCache();
854 $this->saveSettings();
855 }
856
857 /**
858 * Remove the user from the given group.
859 * This takes immediate effect.
860 * @string $group
861 */
862 function removeGroup( $group ) {
863 $dbw =& wfGetDB( DB_MASTER );
864 $dbw->delete( 'user_groups',
865 array(
866 'ug_user' => $this->getID(),
867 'ug_group' => $group,
868 ),
869 'User::removeGroup' );
870
871 $this->mGroups = array_diff( $this->mGroups, array( $group ) );
872 $this->mRights = User::getGroupPermissions( $this->getEffectiveGroups() );
873
874 $this->invalidateCache();
875 $this->saveSettings();
876 }
877
878
879 /**
880 * A more legible check for non-anonymousness.
881 * Returns true if the user is not an anonymous visitor.
882 *
883 * @return bool
884 */
885 function isLoggedIn() {
886 return( $this->getID() != 0 );
887 }
888
889 /**
890 * A more legible check for anonymousness.
891 * Returns true if the user is an anonymous visitor.
892 *
893 * @return bool
894 */
895 function isAnon() {
896 return !$this->isLoggedIn();
897 }
898
899 /**
900 * Check if a user is sysop
901 * Die with backtrace. Use User:isAllowed() instead.
902 * @deprecated
903 */
904 function isSysop() {
905 return $this->isAllowed( 'protect' );
906 }
907
908 /** @deprecated */
909 function isDeveloper() {
910 return $this->isAllowed( 'siteadmin' );
911 }
912
913 /** @deprecated */
914 function isBureaucrat() {
915 return $this->isAllowed( 'makesysop' );
916 }
917
918 /**
919 * Whether the user is a bot
920 * @todo need to be migrated to the new user level management sytem
921 */
922 function isBot() {
923 $this->loadFromDatabase();
924 return in_array( 'bot', $this->mRights );
925 }
926
927 /**
928 * Check if user is allowed to access a feature / make an action
929 * @param string $action Action to be checked (see $wgAvailableRights in Defines.php for possible actions).
930 * @return boolean True: action is allowed, False: action should not be allowed
931 */
932 function isAllowed($action='') {
933 $this->loadFromDatabase();
934 return in_array( $action , $this->mRights );
935 }
936
937 /**
938 * Load a skin if it doesn't exist or return it
939 * @todo FIXME : need to check the old failback system [AV]
940 */
941 function &getSkin() {
942 global $IP;
943 if ( ! isset( $this->mSkin ) ) {
944 $fname = 'User::getSkin';
945 wfProfileIn( $fname );
946
947 # get all skin names available
948 $skinNames = Skin::getSkinNames();
949
950 # get the user skin
951 $userSkin = $this->getOption( 'skin' );
952 if ( $userSkin == '' ) { $userSkin = 'standard'; }
953
954 if ( !isset( $skinNames[$userSkin] ) ) {
955 # in case the user skin could not be found find a replacement
956 $fallback = array(
957 0 => 'Standard',
958 1 => 'Nostalgia',
959 2 => 'CologneBlue');
960 # if phptal is enabled we should have monobook skin that
961 # superseed the good old SkinStandard.
962 if ( isset( $skinNames['monobook'] ) ) {
963 $fallback[0] = 'MonoBook';
964 }
965
966 if(is_numeric($userSkin) && isset( $fallback[$userSkin]) ){
967 $sn = $fallback[$userSkin];
968 } else {
969 $sn = 'Standard';
970 }
971 } else {
972 # The user skin is available
973 $sn = $skinNames[$userSkin];
974 }
975
976 # Grab the skin class and initialise it. Each skin checks for PHPTal
977 # and will not load if it's not enabled.
978 require_once( $IP.'/skins/'.$sn.'.php' );
979
980 # Check if we got if not failback to default skin
981 $className = 'Skin'.$sn;
982 if( !class_exists( $className ) ) {
983 # DO NOT die if the class isn't found. This breaks maintenance
984 # scripts and can cause a user account to be unrecoverable
985 # except by SQL manipulation if a previously valid skin name
986 # is no longer valid.
987 $className = 'SkinStandard';
988 require_once( $IP.'/skins/Standard.php' );
989 }
990 $this->mSkin =& new $className;
991 wfProfileOut( $fname );
992 }
993 return $this->mSkin;
994 }
995
996 /**#@+
997 * @param string $title Article title to look at
998 */
999
1000 /**
1001 * Check watched status of an article
1002 * @return bool True if article is watched
1003 */
1004 function isWatched( $title ) {
1005 $wl = WatchedItem::fromUserTitle( $this, $title );
1006 return $wl->isWatched();
1007 }
1008
1009 /**
1010 * Watch an article
1011 */
1012 function addWatch( $title ) {
1013 $wl = WatchedItem::fromUserTitle( $this, $title );
1014 $wl->addWatch();
1015 $this->invalidateCache();
1016 }
1017
1018 /**
1019 * Stop watching an article
1020 */
1021 function removeWatch( $title ) {
1022 $wl = WatchedItem::fromUserTitle( $this, $title );
1023 $wl->removeWatch();
1024 $this->invalidateCache();
1025 }
1026
1027 /**
1028 * Clear the user's notification timestamp for the given title.
1029 * If e-notif e-mails are on, they will receive notification mails on
1030 * the next change of the page if it's watched etc.
1031 */
1032 function clearNotification( &$title ) {
1033 global $wgUser;
1034
1035 $userid = $this->getID();
1036 if ($userid==0)
1037 return;
1038
1039 // Only update the timestamp if the page is being watched.
1040 // The query to find out if it is watched is cached both in memcached and per-invocation,
1041 // and when it does have to be executed, it can be on a slave
1042 // If this is the user's newtalk page, we always update the timestamp
1043 if ($title->getNamespace() == NS_USER_TALK &&
1044 $title->getText() == $wgUser->getName())
1045 {
1046 $watched = true;
1047 } elseif ( $this->getID() == $wgUser->getID() ) {
1048 $watched = $title->userIsWatching();
1049 } else {
1050 $watched = true;
1051 }
1052
1053 // If the page is watched by the user (or may be watched), update the timestamp on any
1054 // any matching rows
1055 if ( $watched ) {
1056 $dbw =& wfGetDB( DB_MASTER );
1057 $success = $dbw->update( 'watchlist',
1058 array( /* SET */
1059 'wl_notificationtimestamp' => 0
1060 ), array( /* WHERE */
1061 'wl_title' => $title->getDBkey(),
1062 'wl_namespace' => $title->getNamespace(),
1063 'wl_user' => $this->getID()
1064 ), 'User::clearLastVisited'
1065 );
1066 }
1067 }
1068
1069 /**#@-*/
1070
1071 /**
1072 * Resets all of the given user's page-change notification timestamps.
1073 * If e-notif e-mails are on, they will receive notification mails on
1074 * the next change of any watched page.
1075 *
1076 * @param int $currentUser user ID number
1077 * @access public
1078 */
1079 function clearAllNotifications( $currentUser ) {
1080 if( $currentUser != 0 ) {
1081
1082 $dbw =& wfGetDB( DB_MASTER );
1083 $success = $dbw->update( 'watchlist',
1084 array( /* SET */
1085 'wl_notificationtimestamp' => 0
1086 ), array( /* WHERE */
1087 'wl_user' => $currentUser
1088 ), 'UserMailer::clearAll'
1089 );
1090
1091 # we also need to clear here the "you have new message" notification for the own user_talk page
1092 # This is cleared one page view later in Article::viewUpdates();
1093 }
1094 }
1095
1096 /**
1097 * @access private
1098 * @return string Encoding options
1099 */
1100 function encodeOptions() {
1101 $a = array();
1102 foreach ( $this->mOptions as $oname => $oval ) {
1103 array_push( $a, $oname.'='.$oval );
1104 }
1105 $s = implode( "\n", $a );
1106 return $s;
1107 }
1108
1109 /**
1110 * @access private
1111 */
1112 function decodeOptions( $str ) {
1113 $a = explode( "\n", $str );
1114 foreach ( $a as $s ) {
1115 if ( preg_match( "/^(.[^=]*)=(.*)$/", $s, $m ) ) {
1116 $this->mOptions[$m[1]] = $m[2];
1117 }
1118 }
1119 }
1120
1121 function setCookies() {
1122 global $wgCookieExpiration, $wgCookiePath, $wgCookieDomain, $wgDBname;
1123 if ( 0 == $this->mId ) return;
1124 $this->loadFromDatabase();
1125 $exp = time() + $wgCookieExpiration;
1126
1127 $_SESSION['wsUserID'] = $this->mId;
1128 setcookie( $wgDBname.'UserID', $this->mId, $exp, $wgCookiePath, $wgCookieDomain );
1129
1130 $_SESSION['wsUserName'] = $this->mName;
1131 setcookie( $wgDBname.'UserName', $this->mName, $exp, $wgCookiePath, $wgCookieDomain );
1132
1133 $_SESSION['wsToken'] = $this->mToken;
1134 if ( 1 == $this->getOption( 'rememberpassword' ) ) {
1135 setcookie( $wgDBname.'Token', $this->mToken, $exp, $wgCookiePath, $wgCookieDomain );
1136 } else {
1137 setcookie( $wgDBname.'Token', '', time() - 3600 );
1138 }
1139 }
1140
1141 /**
1142 * Logout user
1143 * It will clean the session cookie
1144 */
1145 function logout() {
1146 global $wgCookiePath, $wgCookieDomain, $wgDBname, $wgIP;
1147 $this->loadDefaults();
1148 $this->setLoaded( true );
1149
1150 $_SESSION['wsUserID'] = 0;
1151
1152 setcookie( $wgDBname.'UserID', '', time() - 3600, $wgCookiePath, $wgCookieDomain );
1153 setcookie( $wgDBname.'Token', '', time() - 3600, $wgCookiePath, $wgCookieDomain );
1154
1155 # Remember when user logged out, to prevent seeing cached pages
1156 setcookie( $wgDBname.'LoggedOut', wfTimestampNow(), time() + 86400, $wgCookiePath, $wgCookieDomain );
1157 }
1158
1159 /**
1160 * Save object settings into database
1161 */
1162 function saveSettings() {
1163 global $wgMemc, $wgDBname;
1164 $fname = 'User::saveSettings';
1165
1166 $dbw =& wfGetDB( DB_MASTER );
1167 if ( ! $this->getNewtalk() ) {
1168 # Delete the watchlist entry for user_talk page X watched by user X
1169 $dbw->delete( 'watchlist',
1170 array( 'wl_user' => $this->mId,
1171 'wl_title' => $this->getTitleKey(),
1172 'wl_namespace' => NS_USER_TALK ),
1173 $fname );
1174 if( !$this->mId ) {
1175 # Anon users have a separate memcache space for newtalk
1176 # since they don't store their own info. Trim...
1177 $wgMemc->delete( "$wgDBname:newtalk:ip:{$this->mName}" );
1178 }
1179 }
1180
1181 if ( 0 == $this->mId ) { return; }
1182
1183 $dbw->update( 'user',
1184 array( /* SET */
1185 'user_name' => $this->mName,
1186 'user_password' => $this->mPassword,
1187 'user_newpassword' => $this->mNewpassword,
1188 'user_real_name' => $this->mRealName,
1189 'user_email' => $this->mEmail,
1190 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated ),
1191 'user_options' => $this->encodeOptions(),
1192 'user_touched' => $dbw->timestamp($this->mTouched),
1193 'user_token' => $this->mToken
1194 ), array( /* WHERE */
1195 'user_id' => $this->mId
1196 ), $fname
1197 );
1198 $wgMemc->delete( "$wgDBname:user:id:$this->mId" );
1199 }
1200
1201 /**
1202 * Checks if a user with the given name exists, returns the ID
1203 */
1204 function idForName() {
1205 $fname = 'User::idForName';
1206
1207 $gotid = 0;
1208 $s = trim( $this->mName );
1209 if ( 0 == strcmp( '', $s ) ) return 0;
1210
1211 $dbr =& wfGetDB( DB_SLAVE );
1212 $id = $dbr->selectField( 'user', 'user_id', array( 'user_name' => $s ), $fname );
1213 if ( $id === false ) {
1214 $id = 0;
1215 }
1216 return $id;
1217 }
1218
1219 /**
1220 * Add user object to the database
1221 */
1222 function addToDatabase() {
1223 $fname = 'User::addToDatabase';
1224 $dbw =& wfGetDB( DB_MASTER );
1225 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
1226 $dbw->insert( 'user',
1227 array(
1228 'user_id' => $seqVal,
1229 'user_name' => $this->mName,
1230 'user_password' => $this->mPassword,
1231 'user_newpassword' => $this->mNewpassword,
1232 'user_email' => $this->mEmail,
1233 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated ),
1234 'user_real_name' => $this->mRealName,
1235 'user_options' => $this->encodeOptions(),
1236 'user_token' => $this->mToken
1237 ), $fname
1238 );
1239 $this->mId = $dbw->insertId();
1240 }
1241
1242 function spreadBlock() {
1243 global $wgIP;
1244 # If the (non-anonymous) user is blocked, this function will block any IP address
1245 # that they successfully log on from.
1246 $fname = 'User::spreadBlock';
1247
1248 wfDebug( "User:spreadBlock()\n" );
1249 if ( $this->mId == 0 ) {
1250 return;
1251 }
1252
1253 $userblock = Block::newFromDB( '', $this->mId );
1254 if ( !$userblock->isValid() ) {
1255 return;
1256 }
1257
1258 # Check if this IP address is already blocked
1259 $ipblock = Block::newFromDB( $wgIP );
1260 if ( $ipblock->isValid() ) {
1261 # Just update the timestamp
1262 $ipblock->updateTimestamp();
1263 return;
1264 }
1265
1266 # Make a new block object with the desired properties
1267 wfDebug( "Autoblocking {$this->mName}@{$wgIP}\n" );
1268 $ipblock->mAddress = $wgIP;
1269 $ipblock->mUser = 0;
1270 $ipblock->mBy = $userblock->mBy;
1271 $ipblock->mReason = wfMsg( 'autoblocker', $this->getName(), $userblock->mReason );
1272 $ipblock->mTimestamp = wfTimestampNow();
1273 $ipblock->mAuto = 1;
1274 # If the user is already blocked with an expiry date, we don't
1275 # want to pile on top of that!
1276 if($userblock->mExpiry) {
1277 $ipblock->mExpiry = min ( $userblock->mExpiry, Block::getAutoblockExpiry( $ipblock->mTimestamp ));
1278 } else {
1279 $ipblock->mExpiry = Block::getAutoblockExpiry( $ipblock->mTimestamp );
1280 }
1281
1282 # Insert it
1283 $ipblock->insert();
1284
1285 }
1286
1287 function getPageRenderingHash() {
1288 global $wgContLang;
1289 if( $this->mHash ){
1290 return $this->mHash;
1291 }
1292
1293 // stubthreshold is only included below for completeness,
1294 // it will always be 0 when this function is called by parsercache.
1295
1296 $confstr = $this->getOption( 'math' );
1297 $confstr .= '!' . $this->getOption( 'stubthreshold' );
1298 $confstr .= '!' . $this->getOption( 'editsection' );
1299 $confstr .= '!' . $this->getOption( 'date' );
1300 $confstr .= '!' . $this->getOption( 'numberheadings' );
1301 $confstr .= '!' . $this->getOption( 'language' );
1302 $confstr .= '!' . $this->getOption( 'thumbsize' );
1303 // add in language specific options, if any
1304 $extra = $wgContLang->getExtraHashOptions();
1305 $confstr .= $extra;
1306
1307 $this->mHash = $confstr;
1308 return $confstr ;
1309 }
1310
1311 function isAllowedToCreateAccount() {
1312 global $wgWhitelistAccount;
1313 $allowed = false;
1314
1315 if (!$wgWhitelistAccount) { return 1; }; // default behaviour
1316 foreach ($wgWhitelistAccount as $right => $ok) {
1317 $userHasRight = (!strcmp($right, 'user') || in_array($right, $this->getRights()));
1318 $allowed |= ($ok && $userHasRight);
1319 }
1320 return $allowed;
1321 }
1322
1323 /**
1324 * Set mDataLoaded, return previous value
1325 * Use this to prevent DB access in command-line scripts or similar situations
1326 */
1327 function setLoaded( $loaded ) {
1328 return wfSetVar( $this->mDataLoaded, $loaded );
1329 }
1330
1331 /**
1332 * Get this user's personal page title.
1333 *
1334 * @return Title
1335 * @access public
1336 */
1337 function getUserPage() {
1338 return Title::makeTitle( NS_USER, $this->mName );
1339 }
1340
1341 /**
1342 * Get this user's talk page title.
1343 *
1344 * @return Title
1345 * @access public
1346 */
1347 function getTalkPage() {
1348 $title = $this->getUserPage();
1349 return $title->getTalkPage();
1350 }
1351
1352 /**
1353 * @static
1354 */
1355 function getMaxID() {
1356 $dbr =& wfGetDB( DB_SLAVE );
1357 return $dbr->selectField( 'user', 'max(user_id)', false );
1358 }
1359
1360 /**
1361 * Determine whether the user is a newbie. Newbies are either
1362 * anonymous IPs, or the 1% most recently created accounts.
1363 * Bots and sysops are excluded.
1364 * @return bool True if it is a newbie.
1365 */
1366 function isNewbie() {
1367 return $this->isAnon() || $this->mId > User::getMaxID() * 0.99 && !$this->isAllowed( 'delete' ) && !$this->isBot();
1368 }
1369
1370 /**
1371 * Check to see if the given clear-text password is one of the accepted passwords
1372 * @param string $password User password.
1373 * @return bool True if the given password is correct otherwise False.
1374 */
1375 function checkPassword( $password ) {
1376 global $wgAuth, $wgMinimalPasswordLength;
1377 $this->loadFromDatabase();
1378
1379 // Even though we stop people from creating passwords that
1380 // are shorter than this, doesn't mean people wont be able
1381 // to. Certain authentication plugins do NOT want to save
1382 // domain passwords in a mysql database, so we should
1383 // check this (incase $wgAuth->strict() is false).
1384 if( strlen( $password ) < $wgMinimalPasswordLength ) {
1385 return false;
1386 }
1387
1388 if( $wgAuth->authenticate( $this->getName(), $password ) ) {
1389 return true;
1390 } elseif( $wgAuth->strict() ) {
1391 /* Auth plugin doesn't allow local authentication */
1392 return false;
1393 }
1394 $ep = $this->encryptPassword( $password );
1395 if ( 0 == strcmp( $ep, $this->mPassword ) ) {
1396 return true;
1397 } elseif ( ($this->mNewpassword != '') && (0 == strcmp( $ep, $this->mNewpassword )) ) {
1398 return true;
1399 } elseif ( function_exists( 'iconv' ) ) {
1400 # Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
1401 # Check for this with iconv
1402 $cp1252hash = $this->encryptPassword( iconv( 'UTF-8', 'WINDOWS-1252', $password ) );
1403 if ( 0 == strcmp( $cp1252hash, $this->mPassword ) ) {
1404 return true;
1405 }
1406 }
1407 return false;
1408 }
1409
1410 /**
1411 * Initialize (if necessary) and return a session token value
1412 * which can be used in edit forms to show that the user's
1413 * login credentials aren't being hijacked with a foreign form
1414 * submission.
1415 *
1416 * @param mixed $salt - Optional function-specific data for hash.
1417 * Use a string or an array of strings.
1418 * @return string
1419 * @access public
1420 */
1421 function editToken( $salt = '' ) {
1422 if( !isset( $_SESSION['wsEditToken'] ) ) {
1423 $token = $this->generateToken();
1424 $_SESSION['wsEditToken'] = $token;
1425 } else {
1426 $token = $_SESSION['wsEditToken'];
1427 }
1428 if( is_array( $salt ) ) {
1429 $salt = implode( '|', $salt );
1430 }
1431 return md5( $token . $salt );
1432 }
1433
1434 /**
1435 * Generate a hex-y looking random token for various uses.
1436 * Could be made more cryptographically sure if someone cares.
1437 * @return string
1438 */
1439 function generateToken( $salt = '' ) {
1440 $token = dechex( mt_rand() ) . dechex( mt_rand() );
1441 return md5( $token . $salt );
1442 }
1443
1444 /**
1445 * Check given value against the token value stored in the session.
1446 * A match should confirm that the form was submitted from the
1447 * user's own login session, not a form submission from a third-party
1448 * site.
1449 *
1450 * @param string $val - the input value to compare
1451 * @param string $salt - Optional function-specific data for hash
1452 * @return bool
1453 * @access public
1454 */
1455 function matchEditToken( $val, $salt = '' ) {
1456 return ( $val == $this->editToken( $salt ) );
1457 }
1458
1459 /**
1460 * Generate a new e-mail confirmation token and send a confirmation
1461 * mail to the user's given address.
1462 *
1463 * @return mixed True on success, a WikiError object on failure.
1464 */
1465 function sendConfirmationMail() {
1466 global $wgIP, $wgContLang;
1467 $url = $this->confirmationTokenUrl( $expiration );
1468 return $this->sendMail( wfMsg( 'confirmemail_subject' ),
1469 wfMsg( 'confirmemail_body',
1470 $wgIP,
1471 $this->getName(),
1472 $url,
1473 $wgContLang->timeanddate( $expiration, false ) ) );
1474 }
1475
1476 /**
1477 * Send an e-mail to this user's account. Does not check for
1478 * confirmed status or validity.
1479 *
1480 * @param string $subject
1481 * @param string $body
1482 * @param strong $from Optional from address; default $wgPasswordSender will be used otherwise.
1483 * @return mixed True on success, a WikiError object on failure.
1484 */
1485 function sendMail( $subject, $body, $from = null ) {
1486 if( is_null( $from ) ) {
1487 global $wgPasswordSender;
1488 $from = $wgPasswordSender;
1489 }
1490
1491 require_once( 'UserMailer.php' );
1492 $error = userMailer( $this->getEmail(), $from, $subject, $body );
1493
1494 if( $error == '' ) {
1495 return true;
1496 } else {
1497 return new WikiError( $error );
1498 }
1499 }
1500
1501 /**
1502 * Generate, store, and return a new e-mail confirmation code.
1503 * A hash (unsalted since it's used as a key) is stored.
1504 * @param &$expiration mixed output: accepts the expiration time
1505 * @return string
1506 * @access private
1507 */
1508 function confirmationToken( &$expiration ) {
1509 $fname = 'User::confirmationToken';
1510
1511 $now = time();
1512 $expires = $now + 7 * 24 * 60 * 60;
1513 $expiration = wfTimestamp( TS_MW, $expires );
1514
1515 $token = $this->generateToken( $this->mId . $this->mEmail . $expires );
1516 $hash = md5( $token );
1517
1518 $dbw =& wfGetDB( DB_MASTER );
1519 $dbw->update( 'user',
1520 array( 'user_email_token' => $hash,
1521 'user_email_token_expires' => $dbw->timestamp( $expires ) ),
1522 array( 'user_id' => $this->mId ),
1523 $fname );
1524
1525 return $token;
1526 }
1527
1528 /**
1529 * Generate and store a new e-mail confirmation token, and return
1530 * the URL the user can use to confirm.
1531 * @param &$expiration mixed output: accepts the expiration time
1532 * @return string
1533 * @access private
1534 */
1535 function confirmationTokenUrl( &$expiration ) {
1536 $token = $this->confirmationToken( $expiration );
1537 $title = Title::makeTitle( NS_SPECIAL, 'Confirmemail/' . $token );
1538 return $title->getFullUrl();
1539 }
1540
1541 /**
1542 * Mark the e-mail address confirmed and save.
1543 */
1544 function confirmEmail() {
1545 $this->loadFromDatabase();
1546 $this->mEmailAuthenticated = wfTimestampNow();
1547 $this->saveSettings();
1548 return true;
1549 }
1550
1551 /**
1552 * Is this user allowed to send e-mails within limits of current
1553 * site configuration?
1554 * @return bool
1555 */
1556 function canSendEmail() {
1557 return $this->isEmailConfirmed();
1558 }
1559
1560 /**
1561 * Is this user allowed to receive e-mails within limits of current
1562 * site configuration?
1563 * @return bool
1564 */
1565 function canReceiveEmail() {
1566 return $this->canSendEmail() && !$this->getOption( 'disablemail' );
1567 }
1568
1569 /**
1570 * Is this user's e-mail address valid-looking and confirmed within
1571 * limits of the current site configuration?
1572 *
1573 * If $wgEmailAuthentication is on, this may require the user to have
1574 * confirmed their address by returning a code or using a password
1575 * sent to the address from the wiki.
1576 *
1577 * @return bool
1578 */
1579 function isEmailConfirmed() {
1580 global $wgEmailAuthentication;
1581 $this->loadFromDatabase();
1582 if( $this->isAnon() )
1583 return false;
1584 if( !$this->isValidEmailAddr( $this->mEmail ) )
1585 return false;
1586 if( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() )
1587 return false;
1588 return true;
1589 }
1590
1591 /**
1592 * @param array $groups list of groups
1593 * @return array list of permission key names for given groups combined
1594 * @static
1595 */
1596 function getGroupPermissions( $groups ) {
1597 global $wgGroupPermissions;
1598 $rights = array();
1599 foreach( $groups as $group ) {
1600 if( isset( $wgGroupPermissions[$group] ) ) {
1601 $rights = array_merge( $rights, $wgGroupPermissions[$group] );
1602 }
1603 }
1604 return $rights;
1605 }
1606
1607 /**
1608 * @param string $group key name
1609 * @return string localized descriptive name, if provided
1610 * @static
1611 */
1612 function getGroupName( $group ) {
1613 $key = "group-$group-name";
1614 $name = wfMsg( $key );
1615 if( $name == '' || $name == "&lt;$key&gt;" ) {
1616 return $group;
1617 } else {
1618 return $name;
1619 }
1620 }
1621
1622 /**
1623 * Return the set of defined explicit groups.
1624 * The * and 'user' groups are not included.
1625 * @return array
1626 * @static
1627 */
1628 function getAllGroups() {
1629 global $wgGroupPermissions;
1630 return array_diff(
1631 array_keys( $wgGroupPermissions ),
1632 array( '*', 'user' ) );
1633 }
1634
1635 }
1636
1637 ?>